package com.edu.ujn.myh.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.edu.ujn.myh.dao.IApplyDao;
import com.edu.ujn.myh.domain.ArticleInfo;
import com.edu.ujn.myh.domain.OpinionInfo;
import com.edu.ujn.myh.domain.ProfessorInfo;
import com.edu.ujn.myh.domain.RoleInfo;
import com.edu.ujn.myh.domain.UserInfo;
import com.edu.ujn.myh.domain.UserRoleInfo;
import com.edu.ujn.myh.utils.Pager;
import com.edu.ujn.myh.utils.StringToArray;
/**
 * 
 * @作者 马永华
 * @日期 2010-4-14下午10:42:31
 * @版本 1.0.0
 */
public class ApplyDaoImpl extends HibernateDaoSupport implements IApplyDao {

	// 获得种类列表
	public List getCategory(String sql) {
		List list = this.getHibernateTemplate().find(sql);
		return list;
	}

	// 获得院系列表
	public List getCollege(String sql) {
		List list = this.getHibernateTemplate().find(sql);
		return list;
	}

	// 将申请信息存入数据库
	public void saveApplyInfo(ArticleInfo articleInfo) {
		UserInfo userInfo = articleInfo.getUserInfo();
		String hql = "from UserInfo userInfo where userInfo.userName = '"
				+ userInfo.getUserName() + "'";
		List list = this.getHibernateTemplate().find(hql);
		if (list != null && list.size() > 0) {
			userInfo = (UserInfo) list.get(0);
			articleInfo.setUserInfo(userInfo);
			this.getHibernateTemplate().save(articleInfo);
		}
	}

	// 获得未分配 的稿件列表
	public List getArticleList(String sql) {
		List list = this.getHibernateTemplate().find(sql);
		return list;
	}

	// 获得专家列表
	public List getProfessor(String sql) {
		List list = null;
		list = this.getHibernateTemplate().find(sql);
		return list;
	}

	// 将稿件专家信息存入数据库
	public void saveAP(Map articleMap, Map proffeMap, String processIdStr) {
		Set set = articleMap.keySet();
		for (Iterator iter = set.iterator(); iter.hasNext();) {
			// 得到领域
			String key = (String) iter.next();
			// 得到学科对应的稿件的ID集合
			List articleList = (List) articleMap.get(key);
			// 如果这个领域分配了专家
			if (articleList != null && articleList.size() != 0
					&& proffeMap.containsKey(key)) {
				// 得到专家的ID
				List pId = (List) proffeMap.get(key);
				// 将ID字符串进行分割，得到ID数组
				String processId[] = StringToArray.stringToArray((String) pId
						.get(0), ",");
				// 将对应关系存入数据库
				for (int i = 0; i < articleList.size(); i++) {
					String id = (String) articleList.get(i);
					for (int j = 0; j < processId.length; j++) {
						final String hql = "insert into T_ARTIPROF(PA_ARTICLEID,PA_PROFESSIONERID) values("
								+ id + "," + processId[j] + ")";
						// 存储对应关系
						this.getHibernateTemplate().executeFind(
								new HibernateCallback() {
									public Object doInHibernate(Session session)
											throws HibernateException,
											SQLException {
										Query query = session
												.createSQLQuery(hql);
										query.executeUpdate();
										return null;
									}
								});
					}
					// 更新article的分配状态
					String hql = "update ArticleInfo ai set ai.fpState =" + 1
							+ ",ai.processId ='" + processIdStr
							+"',ai.spState ="+1
							+ "where ai.AId = '" + id + "'";
					this.getHibernateTemplate().bulkUpdate(hql);
				}
			}
		}

	}

	// 获得专家对应文章ID
	public List getProfessArticle(final String sql,final Pager page) {
		return this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(sql);
				int totalCount = query.list().size();
				int currentPage = page.getCurrentPage();
				int pageSize = page.getPageSize();
				page.setTotalPage(totalCount % pageSize == 0 ? totalCount
						/ pageSize : totalCount / pageSize + 1);
				query.setFirstResult((currentPage - 1) * pageSize);
				query.setMaxResults(pageSize);
				List temp = query.list();
				return temp;
			}
		});
	}

	// 更新article
	public void updateArticle(String sql) {
		this.getHibernateTemplate().bulkUpdate(sql);
//		this.getHibernateTemplate().find(sql);
	}
	
//	更新article通过sql
	public void updateArticleUseSQL(final String sql){

		this.getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException,
							SQLException {
						Query query = session.createSQLQuery(sql);
						query.executeUpdate();
						return null;
					}
		});
		
	}
//	查询文章列表
	public List getArticleList(final String sql,final Pager page) {
		return this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(sql);
				int totalCount = query.list().size();
				int currentPage = page.getCurrentPage();
				int pageSize = page.getPageSize();
				page.setTotalPage(totalCount % pageSize == 0 ? totalCount
						/ pageSize : totalCount / pageSize + 1);
				query.setFirstResult((currentPage - 1) * pageSize);
				query.setMaxResults(pageSize);
				List temp = query.list();
				return temp;
			}
		});
	}
	
	// 根据Id更新article
	public List updateArticle(int[] id) {
		List list = new ArrayList();
		for(int i=0;i<id.length;i++){
			String sql = "update ArticleInfo ar set ar.spState ="+5+" where ar.AId = "+id[i];
			this.getHibernateTemplate().bulkUpdate(sql);
			String sql1 = "from ArticleInfo ar where ar.AId = "+id[i];
			List l = this.getHibernateTemplate().find(sql1);
			if(l!=null&&l.size()>0){
				ArticleInfo ai = (ArticleInfo)l.get(0);
				list.add(ai);
			}
		}
		return list;
	}
	
	public List getPrivList() {
		String sql = "from PrivInfo p";
		List list = this.getHibernateTemplate().find(sql);
		return list;
	}
//将文章的分数和专家意见更新
	public void updateArticle(ArticleInfo articleInfo) {
		String sql = "update t_article Set a_score=(( select a_score from t_article where A_ID="
			+ articleInfo.getAId()
			+ " )+"
			+ articleInfo.getScore()
			+ ")/2 where a_id ="
			+ articleInfo.getAId();
		System.out.println(sql);
//		更新分数
		updateArticleUseSQL(sql);
//		更新意见
		OpinionInfo opinionInfo = articleInfo.getOpinionInfo();
//		如果该专家评论过，则更新，否则插入
		String sql1 = "from OpinionInfo op where op.aId ="+opinionInfo.getaId()+" and op.pId="+opinionInfo.getpId();
		System.out.println(sql1);
		List list = this.getHibernateTemplate().find(sql1);
		if(list!=null&&list.size()>0){
			OpinionInfo op = (OpinionInfo)list.get(0);
			opinionInfo.setOId(op.getOId());
			this.getHibernateTemplate().clear();
			this.getHibernateTemplate().update(opinionInfo);
		}else{
		this.getHibernateTemplate().saveOrUpdate(opinionInfo);
		}
	}
//	根据传入的SQL语句进行更新
	public void updatePriv(String sql) {
		this.getHibernateTemplate().bulkUpdate(sql);
	}
//	获得专家意见列表
	public List getOpinionsInfo(String sql) {
		List list = this.getHibernateTemplate().find(sql);
		return list;
	}
//保存对象
	public String saveObject(Object obj) {
		this.getHibernateTemplate().save(obj);
		return null;
	}
// 保存专家信息
	public void saveproInfo(List list) {
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				ProfessorInfo prof = (ProfessorInfo)list.get(i);
				this.getHibernateTemplate().save(prof);
				UserInfo userInfo = new UserInfo();
				userInfo.setUserName(prof.getUserName());
				userInfo.setPassWord(prof.getPassWord());
				userInfo.setRoleId(2);
				UserRoleInfo urInfo = new UserRoleInfo();
				RoleInfo roleInfo = new RoleInfo();
				roleInfo.setId(2);
				this.getHibernateTemplate().save(userInfo);
				urInfo.setUserInfo(userInfo);
				urInfo.setRoleInfo(roleInfo);
				this.getHibernateTemplate().save(urInfo);
			}			
		}
	}
}
